package com.kyxx.topics.activity;

import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.kyxx.topics.BaseActivity;
import com.kyxx.topics.BaseApp;
import com.kyxx.topics.R;
import com.kyxx.topics.bean.AddQuanBean;
import com.kyxx.topics.bean.ArticleBean;
import com.kyxx.topics.net.OkGoRequest;
import com.kyxx.topics.net.ResponseListener;
import com.kyxx.topics.net.RestClient;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.Constants;
import com.kyxx.topics.utils.ToastUtils;
import com.kyxx.topics.widget.CusPtrClassicFrameLayout;
import com.kyxx.topics.widget.ObservableListView;
import com.loopj.android.http.RequestParams;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.request.BaseRequest;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import okhttp3.Call;
import okhttp3.Response;

public class ShopQuanActivity extends BaseActivity {
    private CusPtrClassicFrameLayout ptrv;
    private ObservableListView lvfs;
    private RelativeLayout rl_progress;
    private ProgressBar avi;
    private LinearLayout ll_reload;
    private int pageSize = 1;
    private int countSize = 20;
    private int lastVisiblePosition;
    ShopQuanAdapter shopQuanAdapter;
    private List<AddQuanBean> addQuanBeanList = new ArrayList<>();
    private ImageLoader imageLoader = ImageLoader.getInstance();
    private DisplayImageOptions options = new DisplayImageOptions.Builder()
            // 设置图片在下载期间显示的图片
            .showImageOnLoading(R.mipmap.image_default)
            // 设置图片Uri为空或是错误的时候显示的图片
            .showImageForEmptyUri(R.mipmap.image_default)
            // 设置图片加载/解码过程中错误时候显示的图片
            .showImageOnFail(R.mipmap.image_default)
            .cacheInMemory(true)
            // 设置下载的图片是否缓存在内存中
            .cacheOnDisk(true)
            // 设置下载的图片是否缓存在SD卡中
            .bitmapConfig(Bitmap.Config.RGB_565)// 设置图片的解码类型
            // .displayer(new RoundedBitmapDisplayer(9999))
            .resetViewBeforeLoading(false)
            .build();

    @Override
    protected void loadTopBar(String title) {
        super.loadTopBar(title);
        top_bar_tv_left.setVisibility(View.GONE);
        top_bar_iv_left.setVisibility(View.VISIBLE);
        top_bar_tv_right.setVisibility(View.GONE);
        top_bar_iv_right.setVisibility(View.GONE);
        top_bar_iv_left.setImageDrawable(getResources().getDrawable(R.drawable.ic_arrow_right));
        top_bar_iv_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_shop_quan);
    }

    @Override
    protected void findViewById() {
        loadTopBar("领取优惠券");
        ptrv = (CusPtrClassicFrameLayout) findViewById(R.id.ptrv);
        ptrv.setMode(PtrFrameLayout.Mode.REFRESH);
        ptrv.setLastUpdateTimeHeaderRelateObject(ShopQuanActivity.this);
        ptrv.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(final PtrFrameLayout frame) {
                ptrv.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        pageSize = 1;
                        initList(Constants.REFRESH, pageSize, countSize);
                    }
                }, Constants.DELAYTIMES);
            }
        });
        lvfs = (ObservableListView) findViewById(R.id.lvfs);
        lvfs.setFocusable(false);
        rl_progress = (RelativeLayout) findViewById(R.id.rl_progress);
        avi = (ProgressBar) findViewById(R.id.avi);
        ll_reload = (LinearLayout) findViewById(R.id.ll_reload);
        ll_reload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initList(Constants.INITDATA, pageSize, countSize);
            }
        });

    }

    @Override
    protected void setListener() {
        lvfs.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
                if (lastVisiblePosition == lvfs.getLastVisiblePosition())
                    return;
                lastVisiblePosition = lvfs.getLastVisiblePosition();
                Log.e("topic", lastVisiblePosition + "onScroll" + lvfs.getCount());
                if (lastVisiblePosition == lvfs.getCount() - 2 && lvfs.getCount() >= countSize) {
                    pageSize++;
//                    initList(Constants.LOADMORE, pageSize, countSize);
                }

            }
        });
    }

    @Override
    protected void processLogic() {
        shopQuanAdapter = new ShopQuanAdapter();
        lvfs.setAdapter(shopQuanAdapter);
        initList(Constants.INITDATA, pageSize, countSize);
    }

    class ShopQuanAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return addQuanBeanList.size();
        }

        @Override
        public Object getItem(int i) {
            return addQuanBeanList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {
            final ViewHolder holder;
            if (view == null) {
                holder = new ViewHolder();
                view = View.inflate(context, R.layout.item_quan_add, null);
                holder.tv_name = (TextView) view.findViewById(R.id.tv_name);
                holder.civ_huiyuanka = (ImageView) view.findViewById(R.id.civ_huiyuanka);
                holder.tv_count = (TextView) view.findViewById(R.id.tv_count);
                holder.btn = (Button) view.findViewById(R.id.btn);
                holder.tv_least = (TextView) view.findViewById(R.id.tv_least);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }

            final AddQuanBean bean = addQuanBeanList.get(i);
            holder.tv_name.setText(bean.getTitle());
            imageLoader.displayImage(UrlUtils.BASEHTTP + bean.getImgurl(), holder.civ_huiyuanka, options);
            if (bean.getType() == 1) {//体验券
                holder.tv_count.setText("共可使用" + bean.getTimes() + "次");
            } else if (bean.getType() == 2) {//抵扣券
                holder.tv_count.setText("满" + bean.getJianmian() + "元  " + "抵扣" + bean.getDikou() + "元");
            }
            holder.tv_least.setText("剩余" + bean.getTotal() + "张");
            if (bean.getGet_limit() > bean.getHas_ticked()) {
                holder.btn.setEnabled(true);
                holder.btn.setText("领取");
            } else {
                holder.btn.setEnabled(false);
                holder.btn.setText("已领取");
            }
            holder.btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
                    jsonObject.put("uid", BaseApp.getModel().getId());
                    jsonObject.put("nickname", BaseApp.getModel().getNickname());
                    jsonObject.put("coupon_id", addQuanBeanList.get(i).getId());
                    jsonObject.put("num", "1");
                    RequestParams params = new RequestParams();
                    params.put("json", jsonObject.toString());
                    RestClient.post(UrlUtils.TICKCOUPON, params, context, new ResponseListener(ShopQuanActivity.this, true) {
                        @Override
                        public void success(int arg0, Header[] arg1, org.json.JSONObject result) {
                            ToastUtils.show(context, "成功领取优惠券");
                            bean.setHas_ticked(1);
                            holder.btn.setEnabled(false);
                            holder.btn.setText("已领取");
                            bean.setTotal(Long.valueOf(bean.getTotal()) - 1 + "");
                            holder.tv_least.setText("剩余" + bean.getTotal() + "张");
                        }
                    });
                }
            });
            return view;
        }
    }

    class ViewHolder {
        TextView tv_name;
        ImageView civ_huiyuanka;
        TextView tv_count;
        TextView btn;
        TextView tv_least;
    }

    private void initList(final int type, int page, int count) {
        HttpParams params = new HttpParams();
        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        jsonObject.put("uid", BaseApp.getModel().getId());
        jsonObject.put("shop_id", getIntent().getStringExtra("shop_id"));
//        jsonObject.put("shop_id", 0);
        params.put("json", jsonObject.toString());
        String cacheKey = UrlUtils.getAllCoupon + "&uid=" + BaseApp.getModel().getId() + "&shoId=" + getIntent().getStringExtra("shopId");
        OkGoRequest.post(UrlUtils.getAllCoupon, ShopQuanActivity.this, cacheKey, CacheMode.REQUEST_FAILED_READ_CACHE, params, new StringCallback() {
            @Override
            public void onBefore(BaseRequest request) {
                super.onBefore(request);
                switch (type) {
                    case Constants.INITDATA:
                        rl_progress.setVisibility(View.VISIBLE);
                        avi.setVisibility(View.VISIBLE);
                        ll_reload.setVisibility(View.GONE);
                        break;
                    default:
                        rl_progress.setVisibility(View.GONE);
                        break;
                }
            }

            @Override
            public void onCacheSuccess(String s, Call call) {
                super.onCacheSuccess(s, call);
                onSuccess(s, call, null);
            }

            @Override
            public void onCacheError(Call call, Exception e) {
                super.onCacheError(call, e);
                switch (type) {
                    case Constants.INITDATA:
                        rl_progress.setVisibility(View.VISIBLE);
                        avi.setVisibility(View.GONE);
                        ll_reload.setVisibility(View.VISIBLE);
                        break;
                    default:
                        rl_progress.setVisibility(View.GONE);
                        break;
                }

            }

            @Override
            public void onAfter(String s, Exception e) {
                super.onAfter(s, e);
                ptrv.refreshComplete();
            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                rl_progress.setVisibility(View.GONE);
                try {
                    JSONObject result = new JSONObject(s);
                    if(result.getInt("code")!=0){
                        ToastUtils.show(context,result.getJSONObject("msg").toString());
                        return;
                    }
                    switch (type) {
                        case Constants.INITDATA:
                            addQuanBeanList = JSON.parseArray(result.getJSONArray("data").toString(), AddQuanBean.class);
                            shopQuanAdapter = new ShopQuanAdapter();
                            lvfs.setAdapter(shopQuanAdapter);
                            break;
                        case Constants.LOADMORE:
                            addQuanBeanList.addAll(JSON.parseArray(result.getJSONArray("data").toString(), AddQuanBean.class));
                            shopQuanAdapter.notifyDataSetChanged();
                            break;
                        case Constants.REFRESH:
                            addQuanBeanList = JSON.parseArray(result.getJSONArray("data").toString(), AddQuanBean.class);
                            shopQuanAdapter = new ShopQuanAdapter();
                            lvfs.setAdapter(shopQuanAdapter);
                            break;
                    }
                    lastVisiblePosition = lvfs.getLastVisiblePosition();
                    if (addQuanBeanList == null || addQuanBeanList.size() == 0) {
                        rl_progress.setVisibility(View.VISIBLE);
                        findViewById(R.id.ll_no).setVisibility(View.VISIBLE);
                        avi.setVisibility(View.GONE);
                        ll_reload.setVisibility(View.GONE);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    rl_progress.setVisibility(View.VISIBLE);
                    findViewById(R.id.ll_no).setVisibility(View.VISIBLE);
                    avi.setVisibility(View.GONE);
                    ll_reload.setVisibility(View.GONE);
                }
            }
        });
    }
}
